package com.my.springbootfile.service.impl;

import com.my.springbootfile.service.FileService;
import com.my.springbootfile.vo.ZipFileInVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static java.util.stream.Collectors.toList;

/**
 * @author: marshal
 * @date: 2021-08-23 5:29 PM
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    /**
     * 获取当前系统的临时目录
     */
    private static final String FILE_PATH = System.getProperty("java.io.tmpdir") + File.separator;

    private static final int ZIP_BUFFER_SIZE = 8192;

    @Override
    public void zipFileDownload(HttpServletResponse response, ZipFileInVO inVO) {
        List<File> fileList = inVO.getFilenames().stream().map(s -> new File("./uploads/" + s)).collect(toList()).stream().filter(file -> file.exists()).collect(toList());
        // zip文件路径
        String zipPath = FILE_PATH + inVO.getZipFilename();
        try {
            //创建zip输出流
            try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath))) {
                //声明文件集合用于存放文件
                byte[] buffer = new byte[1024];
                //将文件放入zip压缩包
                for (int i = 0; i < fileList.size(); i++) {
                    File file = fileList.get(i);
                    try (FileInputStream fis = new FileInputStream(file)) {
                        out.putNextEntry(new ZipEntry(file.getName()));
                        int len;
                        // 读入需要下载的文件的内容，打包到zip文件
                        while ((len = fis.read(buffer)) > 0) {
                            out.write(buffer, 0, len);
                        }
                        out.closeEntry();
                    }
                }
            }
            //下载zip文件
            download(response, inVO.getZipFilename());
        } catch (Exception e) {
            log.error("文件下载出错", e);
        } finally {
            // zip文件删除
            File zipFile = new File(zipPath);
            if (zipFile.exists()) {
                zipFile.delete();
            }
        }
    }

    @Override
    public void download(HttpServletResponse response, String filename) {
        try {
            String path = FILE_PATH + filename;
            File file = new File(path);
            if (file.exists()) {
                try (InputStream ins = new FileInputStream(path);
                     BufferedInputStream bins = new BufferedInputStream(ins);
                     OutputStream outs = response.getOutputStream();
                     BufferedOutputStream bouts = new BufferedOutputStream(outs)) {
                    response.setContentType("application/x-download");
                    response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
                    int bytesRead = 0;
                    byte[] buffer = new byte[ZIP_BUFFER_SIZE];
                    while ((bytesRead = bins.read(buffer, 0, ZIP_BUFFER_SIZE)) != -1) {
                        bouts.write(buffer, 0, bytesRead);
                    }
                    bouts.flush();
                }
            }
        } catch (Exception e) {
            log.error("文件下载出错", e);
        }

    }

}
